package com.haredot.controller;

import com.haredot.entity.SvipConfig;
import com.haredot.service.SVipService;
import com.haredot.validation.Insert;
import com.haredot.validation.Update;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/svip")
public class SVipController {

    private SVipService svipService ;

    public SVipController(SVipService svipService) {
        this.svipService = svipService ;
    }

    /**
     * 添加 SVIP 套餐
     * @param svipConfig
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('svip:add')")
    public R<?> addSvipConfig(@RequestBody @Validated(Insert.class) SvipConfig svipConfig) {
        return svipService.saveSvipConfig(svipConfig);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('svip:modify')")
    public R<?> updateSvipConfig(@PathVariable("id") Long id, @RequestBody @Validated(Update.class) SvipConfig svipConfig) {

        Assert.isTrue(Objects.equals(id, svipConfig.getId()), "ID参数不正确");

        return svipService.updateSvipConfig(svipConfig);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('svip:remove')")
    public R<?> removeSvipConfig(@PathVariable("id") Long id) {
        return svipService.removeById(id) ? R.ok().build() : R.fail().build();
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('svip:batch:remove')")
    public R<?> removeBatchSvipConfig(@RequestBody List<Long> ids) {
        return svipService.removeBatchByIds(ids) ? R.ok().build() : R.fail().build();
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('svip')")
    public R<SvipConfig> querySvipConfigs() {
        List<SvipConfig> list = svipService.list();
        return R.<SvipConfig>ok().data(list);
    }

}
